const express = require('express');
const path = require('path');
const fs = require('fs');

const authRoutes = require('./routes/authRoutes');
const uploadRoutes = require('./routes/uploadRoutes');

// 日志
const logger = require('./config/logger');
const loggerMiddleware = require('./middleware/loggerMiddleware');
const responseMiddleware = require('./middleware/responseMiddleware');

const app = express();
// 创建上传目录
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}
// http://localhost:7878/uploads/xxx.jpg
app.use('/uploads', express.static('uploads'));

// 中间件
app.use(express.json());
app.use(loggerMiddleware);
app.use(responseMiddleware);

// 路由
app.use('/api/auth', authRoutes);
app.use('/api/upload', uploadRoutes);

// 全局错误处理
app.use((err, req, res, next) => {
  logger.error('应用错误:', err);
  res.status(500).json({
    code: 500,
    message: '服务器内部错误',
    success: false
  });
});

// 测试接口
app.get('/test', (req, res) => {
  res.json({ message: '测试接口' });
});

const PORT = process.env.PORT || 7878;
app.listen(PORT, () => {
  logger.info(`服务器运行在端口 ${PORT}`);
});

// 捕获未处理的异常
process.on('uncaughtException', (error) => {
  logger.error('未捕获的异常:', error);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('未处理的Promise拒绝:', reason);
});